package com.carlinfo.myjdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

/**
 * 模拟一下事务
 * @author CRG-LENOVO
 *
 */
public class TransactionMain
{
	public static void main(String[] args)
	{
		DbUtil dbUtil = new DbUtil();
		Connection conn = dbUtil.getConnection();
		String sql = "update mydata set name = concat(name,?) where id =1 ;";
		ResultSet rs = null;
		PreparedStatement pst =null;
		try
		{
			Boolean flag = conn.getAutoCommit();
			conn.setAutoCommit(false);
			pst = conn.prepareStatement(sql);
			pst.setObject(1, "=");
			int res = pst.executeUpdate();
			System.out.println("影响条数:"+res);
			pst.close();
			sql = "select * fom mydata;";
			pst = conn.prepareStatement(sql);
			rs = pst.executeQuery();
			conn.commit();
			conn.setAutoCommit(flag);
			while(rs.next())
			{
				String name = rs.getString("name");
				Date publicTime = rs.getTimestamp("publicTime");
				System.out.println(name+"\t"+publicTime);
			}
		} catch (SQLException e)
		{
			e.printStackTrace();
		} catch(Exception e)
		{
			if(conn!=null)
			{
				try
				{
					System.out.println("我回滚了");
					conn.rollback();
				} catch (SQLException e1)
				{
					e1.printStackTrace();
				}
			}
			e.printStackTrace();
		} finally
		{
			dbUtil.closeAll(pst, conn, rs);
		}
	}
}
